import React, { Component } from 'react';
import CustomForm from '../../../components/CustomForm';
import { message, Select } from 'antd';
import services from '../../../services/api';

class CopyField extends Component {
  constructor(props) {
    super(props);
    this.form = null;
    this.state = {
      events: []
    };
  }

  componentWillMount() {}

  handleSubmit = () => {
    this.form.validateFields((err, values) => {
      if (!err) {
        const params = {
          field_ids: this.props.field_ids,
          event_id: values.event_id,
          app_id: values.app_id
        };
        services.field.copy(params).then(data => {
          if (data.code === 0) {
            message.success(data.msg);
            if (this.props.closeModal) {
              this.props.closeModal();
            }
          } else {
            message.error(data.msg);
          }
        });
      }
    });
  };

  handleConfirmBlur = e => {
    const { value } = e.target;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  };

  // 根据app_id获取对应的事件列表
  getEventCodeList = app_id => {
    services.event.getEventCodeList({ app_id: app_id || '-1' }).then(res => {
      if (res.code === 0) {
        this.setState({
          events: res.data
        });
        this.form.setFieldsValue({
          event_id: ''
        });
      }
    });
  };

  render() {
    const formItems = [
      {
        label: {
          label: '渠道'
        },
        name: 'app_id',
        span: 24,
        options: {
          initialValue: this.props.app_id,
          rules: [{ required: true, message: '请选择' }]
        },
        component: (
          <Select placeholder='请选择' onChange={this.getEventCodeList}>
            {this.props.applications.map(item => {
              return (
                <Select.Option value={item.app_id} key={item.app_id}>
                  {item.app_name}
                </Select.Option>
              );
            })}
          </Select>
        )
      },
      {
        label: {
          label: '事件'
        },
        name: 'event_id',
        span: 24,
        options: {
          initialValue: this.props.event_id,
          rules: [{ required: true, message: '请选择' }]
        },
        component: (
          <Select placeholder='请选择'>
            {this.state.events
              .filter(it => it.event_id !== -1)
              .map(item => {
                return (
                  <Select.Option value={item.event_id} key={item.event_id}>
                    {item.event_name}
                  </Select.Option>
                );
              })}
          </Select>
        )
      }
    ];

    return (
      <CustomForm
        closeModal={this.props.closeModal}
        createForm={ref => (this.form = ref)}
        formItems={formItems}
        colNum={1}
        onHandleSubmit={this.handleSubmit}
      />
    );
  }
}

export default CopyField;
